package com.app.couponsharelife.ui.main.nativelife.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.google.android.material.appbar.AppBarLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.home.search.SearchSelecteActivity
import com.app.couponsharelife.ui.view.ScaleTransitionPagerTitleView
import com.app.couponsharelife.ui.viewfactory.NativeLifeFragFactory
import com.app.couponsharelife.utils.AppUtils
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_nativelife.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
/**
 *Created by xct on 2018/12/25
 *Description:本地生活页面
 */
class NativeLifeFragment:LazyFragment(),TencentLocationListener {
    private var locationManager: TencentLocationManager? = null
    private var newHomeFactory: NativeLifeFragFactory?=null
    private var commonNavigator:CommonNavigator?=null
    var bannerList= arrayListOf<LifeTopBanner>()
    var classList= arrayListOf<Classify>()
    var centerBannerList= arrayListOf<CenterBanner>()
    private var merchantClassList= arrayListOf<TradingArea>()
    companion object {
        fun newInstance(): NativeLifeFragment {
            val fragment = NativeLifeFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() =R.layout.fragment_nativelife

    override fun initViews() {
        newHomeFactory=NativeLifeFragFactory()
        nativelifefrag_toolbar.title=AppUtils.getString("CityName","杭州市")
        nativelifefrag_appbarlayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            if (verticalOffset<1&&verticalOffset>-255){
//                nativelifefrag_cityxian.background.alpha=255+verticalOffset
                nativelifefrag_tvweather.setTextColor(Color.argb(255+verticalOffset, 255, 255, 255))
            }else{
//                nativelifefrag_cityxian.background.alpha=0
                nativelifefrag_tvweather.setTextColor(Color.argb(0, 255, 255, 255))
            }
        })
        nativelifefrag_llsousuo.setOnClickListener {
            val intent=Intent(activity,SearchSelecteActivity::class.java)
            intent.putExtra("Type",1)
            startActivity(intent)
        }
        nativelifefrag_toolbar.setNavigationOnClickListener {
            activity!!.finish()
        }
    }

    private fun initLocation() {
        val request = TencentLocationRequest.create()
        request.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
        locationManager = TencentLocationManager.getInstance(context)
        val error = locationManager?.requestLocationUpdates(request, this)
        /*if (error != 0) {
            locationManager?.removeUpdates(this@NativeLifeFragment)
            println("注册失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            AppUtils.setString("CityName", "杭州市")
            nativelifefrag_toolbar.title="杭州市"
        }*/
        /*Observable.create<Int> {
            val request = TencentLocationRequest.create()
            request.requestLevel = TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA
            locationManager = TencentLocationManager.getInstance(context)
            val error = locationManager?.requestLocationUpdates(request, this)
            it.onNext(error!!)
        }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(object :DisposableObserver<Int>(){
            override fun onComplete() {

            }

            override fun onNext(error: Int) {
                if (error != 0) {
                    locationManager?.removeUpdates(this@NativeLifeFragment)
                    println("注册失败 $error")
                    AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
                    AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
                    AppUtils.setString("CityName", "杭州市")
                    nativelifefrag_toolbar.title="杭州市"
                }
            }

            override fun onError(e: Throwable) {
                Log.e("eee","---->${e.toString()}")
            }
        })*/
    }
    override fun lazyLoad() {
        getBaseData()
        //nativelifefrag_viewpager.post { initLocation() }
    }
    private fun setViewPager(){
        nativelifefrag_viewpager.offscreenPageLimit=6
        nativelifefrag_viewpager.adapter=object : FragmentPagerAdapter(childFragmentManager){
            override fun getItem(position: Int): Fragment {
                return newHomeFactory!!.createFragment(position,merchantClassList[position])
            }

            override fun getCount(): Int {
                return merchantClassList.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return merchantClassList[position].name
            }
        }
        commonNavigator= CommonNavigator(activity)
        commonNavigator!!.adapter=object : CommonNavigatorAdapter(){
            override fun getTitleView(p0: Context, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView= ScaleTransitionPagerTitleView(p0,0.8f)
                colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.white)
                colorTransitionPagerTitleView.textSize=25f
                colorTransitionPagerTitleView.paint.isFakeBoldText=true
                colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.white)
                colorTransitionPagerTitleView.text = merchantClassList[p1].name
                colorTransitionPagerTitleView.setOnClickListener { nativelifefrag_viewpager.currentItem = p1 }
                return colorTransitionPagerTitleView
            }

            override fun getCount(): Int {
                return merchantClassList.size
            }

            override fun getIndicator(p0: Context?): IPagerIndicator? {
                /*val indicator=LinePagerIndicator(p0)
                indicator.setColors(resources.getColor(R.color.act_main_bot_nav_select_text_color))*/
                return null
            }
        }
        nativelifefrag_tablayout.navigator=commonNavigator
        ViewPagerHelper.bind(nativelifefrag_tablayout, nativelifefrag_viewpager)
        //nativelifefrag_viewpager.post { initLocation() }
    }
    private fun getBaseData(){
        showProgressDialog("加载中...")
        val map=HashMap<String,String>()
        RetrofitWorker.retrofitWorker.lifeGetBase(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<LifeBaseBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<LifeBaseBean>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            if (it.data!=null){
                                if (it.data!!.topBanner!=null){
                                    bannerList.clear()
                                    bannerList.addAll(it.data!!.topBanner as ArrayList<LifeTopBanner>)
                                    classList.clear()
                                    classList.addAll(it.data!!.classify as ArrayList<Classify>)
                                    centerBannerList.clear()
                                    centerBannerList.addAll(it.data!!.centerBanner as ArrayList<CenterBanner>)
                                    merchantClassList.clear()
                                    val mTradingArea=TradingArea()
                                    mTradingArea.name="推荐"
                                    merchantClassList.add(mTradingArea)
                                    merchantClassList.addAll(it.data!!.tradingArea as ArrayList<TradingArea>)
                                    setViewPager()
                                }
                            }
                        }
                    }
                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    override fun onStatusUpdate(name: String?, error: Int, desc: String?) {
        if (name == "wifi" && error == 5) {
            showToastMsg("请打开GPS定位")
        }
    }

    override fun onLocationChanged(location: TencentLocation?, error: Int, reason: String?) {
        if (TencentLocation.ERROR_OK == error && location != null) {
            println(location)
            /*if (location.city.contains("金华")||location.city.contains("义乌")) {
                println("定位在 义乌")
                AppUtils.setString("Longitude", location.longitude.toString())
                AppUtils.setString("Latitude", location.latitude.toString())
            } else {
                println("定位不在 义乌")
                AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
                AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            }*/
            AppUtils.setString("Longitude", location.longitude.toString())
            AppUtils.setString("Latitude", location.latitude.toString())
            AppUtils.setString("CityName", location.city)
            nativelifefrag_toolbar.title=location.city
        } else {
            println("定位失败 $error")
            AppUtils.setString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
            AppUtils.setString("Latitude", Contacts.HZ_CENTER_LATITUDE)
            AppUtils.setString("CityName", "杭州市")
            nativelifefrag_toolbar.title="杭州市"
        }
        //Log.e("eeee","---->定位结束")
        locationManager?.removeUpdates(this)
    }
}